﻿@namespace Oqtane.Modules.Admin.Users
@inherits ModuleBase
@inject IUserRoleService UserRoleService
@inject IUserService UserService
@inject ISettingService SettingService

@if (userroles == null)
{
    <p>
        <em>Loading...</em>
    </p>
}
else
{
    <ActionLink Action="Add" Text="Add User"/>

    <div class="d-flex p-1">
        <input class="form-control mr-4" @bind="@_search"/><button class="btn btn-outline-primary ml-1" @onclick="OnSearch">Search</button>
    </div>

    <Pager Items="@userroles">
        <Header>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th style="width: 1px;">&nbsp;</th>
            <th>Name</th>
        </Header>
        <Row>
            <td>
                <ActionLink Action="Edit" Parameters="@($"id=" + context.UserId.ToString())"/>
            </td>
            <td>
                <ActionDialog Header="Delete User" Message="@("Are You Sure You Wish To Delete " + context.User.DisplayName + "?")" Action="Delete" Security="SecurityAccessLevel.Admin" Class="btn btn-danger" OnClick="@(async () => await DeleteUser(context))"/>
            </td>
            <td>
                <ActionLink Action="Roles" Parameters="@($"id=" + context.UserId.ToString())"/>
            </td>
            <td>@context.User.DisplayName</td>
        </Row>
    </Pager>
}

@code {
    private List<UserRole> allroles;
    private List<UserRole> userroles;
    private string _search;

    public override SecurityAccessLevel SecurityAccessLevel => SecurityAccessLevel.Admin;

    protected override async Task OnInitializedAsync()
    {
        allroles = await UserRoleService.GetUserRolesAsync(PageState.Site.SiteId);
        await LoadSettingsAsync();
        userroles = Search(_search);
    }

    private List<UserRole> Search(string search)
    {
        if (string.IsNullOrEmpty(_search))
        {
            return allroles.Where(item => item.Role.Name == RoleNames.Registered).ToList();
        }
        return allroles
            .Where(item => item.Role.Name == RoleNames.Registered &&
                           (
                               item.User.Username.Contains(search, StringComparison.OrdinalIgnoreCase) ||
                               item.User.Email.Contains(search, StringComparison.OrdinalIgnoreCase) ||
                               item.User.DisplayName.Contains(search, StringComparison.OrdinalIgnoreCase)
                               )
            )
            .ToList();
    }

    private async Task OnSearch()
    {
        userroles = Search(_search);
        await UpdateSettingsAsync();
    }

    private async Task DeleteUser(UserRole UserRole)
    {
        try
        {
            var user = await UserService.GetUserAsync(UserRole.UserId, PageState.Site.SiteId);
            if (user != null)
            {
                await UserService.DeleteUserAsync(user.UserId);
                await logger.LogInformation("User Deleted {User}", UserRole.User);
                StateHasChanged();
            }
        }
        catch (Exception ex)
        {
            await logger.LogError(ex, "Error Deleting User {User} {Error}", UserRole.User, ex.Message);
            AddModuleMessage(ex.Message, MessageType.Error);
        }
    }

    private string settingSearch = "AU-search";

    private async Task LoadSettingsAsync()
    {
        Dictionary<string, string> settings = await SettingService.GetUserSettingsAsync(PageState.User.UserId);
        _search = SettingService.GetSetting(settings, settingSearch, "");
    }

    private async Task UpdateSettingsAsync()
    {
        Dictionary<string, string> settings = await SettingService.GetUserSettingsAsync(PageState.User.UserId);
        SettingService.SetSetting(settings, settingSearch, _search);
        await SettingService.UpdateUserSettingsAsync(settings, PageState.User.UserId);
    }

}
